<template>
  <div>
    <div style="padding: 20px">
      <el-card>
        <div class="body">
          <elform
            @search="search"
            @add="add"
            :btnName="'新增权限组'"
            :placeholder="'根据用户名搜索'"
            :label="''"
          ></elform>

          <elalert :counts="counts"></elalert>

          <el-table
            :data="list"
            style="width: 100%"
            :row-key="
              row => {
                return row.id
              }
            "
          >
            <el-table-column
              type="selection"
              width="55"
              :resizable="false"
              :reserve-selection="true"
              select-on-indeterminate="true"
            />
            <el-table-column align="center" prop="title" label="用户名" />
            <el-table-column align="left" prop="create_date" label="日期" />
            <el-table-column align="center" label="操作" width="120">
              <template #default="{ row }">
                <el-button type="primary" circle plain @click="edit(row)">
                  <i class="el-icon-edit"></i
                ></el-button>
                <el-button
                  type="danger"
                  circle
                  plain
                  style="margin-left: 9px"
                  @click="del(row)"
                >
                  <i class="el-icon-delete"></i
                ></el-button>
              </template>
            </el-table-column>
          </el-table>

          <elpagination
            :counts="counts"
            :data="data"
            :n="[10, 20, 30, 50]"
            @handleSizeChange="handleSizeChange"
            @handleCurrentChange="handleCurrentChange"
          ></elpagination>
        </div>
      </el-card>
    </div>
    <!-- 弹窗 -->
    <el-dialog :title="title" :visible.sync="showDialog" @close="resetFields">
      <el-form ref="addRef" :model="addFormdata" :rules="rules">
        <el-form-item label-width="120px" label="用户名" prop="title"
          ><el-input v-model="addFormdata.title"></el-input>
        </el-form-item>
        <el-form-item prop="permissions" label-width="120px" label="权限分配"
          ><el-tree
            ref="tree"
            node-key="id"
            :default-expanded-keys="[1]"
            :data="menus"
            :props="menusProps"
            show-checkbox
            @check-change="handleCheckChange"
          >
          </el-tree
        ></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import elform from '@/components/form/index.vue'
import elalert from '@/components/elalert/index.vue'
import elpagination from '@/components/elpagination/index.vue'
import { list as menusList } from '@/api/base/menus'
import {
  simple,
  list,
  add,
  remove,
  detail,
  update
} from '@/api/base/permissions'
import { tranListToTreeData } from '@/utils/index'
import moment from 'moment'
export default {
  data() {
    return {
      data: {
        page: 1,
        pagesize: 10,
        title: ''
      },
      list: [],
      currentPage: 1,
      counts: 1,
      showDialog: false,
      title: '创建用户',
      addFormdata: {
        title: '',
        permissions: []
      },
      row: {},
      menus: [
        {
          id: 1,
          pid: null,
          title: '系统菜单和页面权限点',
          ischeck: false,
          childs: [{ points: [], title: '', pid: '', id: '' }]
        }
      ],
      menusProps: { label: 'title', children: 'childs' },
      rules: {
        title: [{ required: true, massage: '请输入用户名', triggers: 'blur' }]
      }
    }
  },
  components: { elform, elalert, elpagination },
  created() {
    // this.getRoleList()
    this.getList()
    this.getmenusList()
  },
  methods: {
    async getRoleList() {
      await simple()
    },
    // 获取权限组数据
    async getList() {
      const { data } = await list(this.data)
      data.list.forEach(item => {
        item.isCheck = false
        item.create_date = moment(item.create_date).format('YYYY-MM-DD')
      })
      this.list = data.list
      this.counts = data.counts
      this.data.page = data.page
      this.data.pagesize = data.pagesize
    },
    // 获取tree数据
    async getmenusList() {
      const res = await menusList()
      const a = tranListToTreeData(res.data, null)
      a.forEach(item1 => {
        item1.ischeck = false
        for (let key1 in item1) {
          if (key1 === 'childs') {
            item1[key1].forEach(item2 => {
              item2.ischeck = false
              for (let key2 in item2) {
                if (key2 === 'points') {
                  item2.childs = item2.points
                  item2.childs.forEach(item3 => (item3.ischeck = false))
                }
              }
            })
          }
        }
      })
      this.menus[0].childs = a
    },
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate)
      this.addFormdata.permissions.push(data.id)
    },
    handleNodeClick(data) {
      console.log(data)
    },
    handleSizeChange(val) {
      this.data.pagesize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.data.page = val
      this.getList()
    },
    resetFields() {
      this.$refs.addRef.resetFields()
      this.$refs.tree.setCheckedKeys([])
      this.$refs.tree.setChecked(false)
      this.getmenusList()
    },
    search(payload) {
      console.log(payload)
      this.data.title = payload
      this.getList()
    },
    async add() {
      this.title = '创建权限组'
      this.showDialog = true
    },
    async save() {
      if (this.title === '创建权限组') {
        try {
          await this.$refs.addRef.validate()
          await add(this.addFormdata)
          this.getList()
          this.$message.success('创建成功')
          this.addFormdata.permissions = []
        } catch (error) {
          console.log(error)
        }
      } else if (this.title === '编辑权限组') {
        try {
          await this.$refs.addRef.validate()
          await update(this.row)
          this.getList()
          this.$message.success('编辑成功')
        } catch (error) {
          console.dir(error)
        }
      }
      this.showDialog = false
    },
    async edit(row) {
      this.title = '编辑权限组'
      this.showDialog = true
      const { data } = await detail({ id: row.id })
      console.log(data)
      this.row = data
      this.addFormdata.permissions = data.permissions
      this.addFormdata.title = data.title
      for (let i = 0; i < data.permissions.length; i++) {
        this.$nextTick(() => {
          this.$refs.tree.setChecked(data.permissions[i], true, false)
        })
      }
    },
    async del(row) {
      this.$confirm('该项操作不可恢复！确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await remove(row)
          this.$message.success('删除成功')
          this.getList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除'
          })
        })
    }
  },
  computed: {}
}
</script>

<style scoped lang="scss">
.el-card {
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  padding: 20px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  color: #303133;
  -webkit-transition: 0.3s;
  transition: 0.3s;
  border-radius: 4px;
  overflow: hidden;
  .body {
    width: 100%;
    -webkit-font-smoothing: antialiased;
    text-rendering: optimizeLegibility;
    font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
      Microsoft YaHei, Arial, sans-serif;

    ::v-deep .el-table {
      .el-table--fit {
        border-right: 0;
        border-bottom: 0;
      }
    }
    ::v-deep .el-table th.el-table__cell.is-leaf {
      border-bottom: 2px solid #e8e8e8;
      background-color: #fafafa;
    }
    ::v-deep .el-card .body[data-v-eacc1416] .el-table td.el-table__cell div {
      display: flex;
      padding-left: 5px;
      padding-right: 5px;
      box-sizing: border-box;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: normal;
      word-break: break-all;
      line-height: 23px;
    }
  }
}
.el-dialog {
  .el-form .el-form-item {
    width: 400px;
    margin-left: 120px;
  }
  .dialog-footer {
    padding: 10px 20px 20px;
  }
  .el-input {
    width: 100%;
    display: inline-block;
  }
}
</style>
